
package com.jf.cloud.service.sysmanager.remote;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.catalina.valves.CrawlerSessionManagerValve;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codehaus.jackson.type.TypeReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jf.cloud.service.sysmanager.common.base.AjaxPageData;
import com.jf.cloud.service.sysmanager.common.base.OPaging;
import com.jf.cloud.service.sysmanager.common.db.BaseDao;
import com.jf.cloud.service.sysmanager.common.db.Query;
import com.jf.cloud.service.sysmanager.common.taglib.Paging;
import com.jf.cloud.service.sysmanager.common.util.DateUtil;
import com.jf.cloud.service.sysmanager.common.util.JsonUtil;
import com.jf.cloud.service.sysmanager.common.util.StringUtil;
import com.jf.cloud.service.sysmanager.dao.ICardUserService;
import com.jf.cloud.service.sysmanager.entity.CardBaseGetCode;
import com.jf.cloud.service.sysmanager.entity.CardBuguUserInfo;
import com.jf.cloud.service.sysmanager.entity.CardUser;
import com.jf.cloud.service.sysmanager.entity.SysStaff;
import com.jf.cloud.service.sysmanager.handler.ExcelHandler;
import com.jf.cloud.service.sysmanager.handler.TokenHandler;
import com.jf.cloud.service.sysmanager.support.entity.Result;
import com.jf.cloud.service.sysmanager.support.web.BaseController;
import com.jf.cloud.service.sysmanager.util.CodeUtil;

/**
 * 员工控制器
 *
 * @author 代码机1.0 创建时间：2018-03-31
 */
@Controller
@RequestMapping("/cardUser")
public class CardUserController extends BaseController {

    /**
     * 日志
     */
    private static Log log = LogFactory.getLog(CardUserController.class);

    @Autowired
    private TokenHandler tokenHandler;
    @Autowired
    private ICardUserService cardUserService;

    @Autowired
    private ExcelHandler excelHandler;
    
    @Resource
    private BaseDao baseDao;
    
    /**
     * 添加用户信息
     *
     * @author 朱建文 创建时间：2018年4月17日 下午5:11:56
     */
    @ResponseBody
    @RequestMapping("/add")
    public Result add(CardUser cardUser, String token, HttpServletRequest request) {
        try {
            SysStaff sysStaff = tokenHandler.getSysStaffInfoByToken(token);
            if (sysStaff == null) {
                return new Result.ResultBuiler().failed("登录状态失效");
            }
            if (StringUtil.isEmpty(cardUser.getUserEmail()) || StringUtil.isEmpty(cardUser.getUserName()) || StringUtil.isEmpty(cardUser.getUserKey())
                    || StringUtil.isEmpty(cardUser.getLoginPwd()) || StringUtil.isEmpty(cardUser.getPayPwd()) || cardUser.getPlatformType() == null
                    || cardUser.getUserEnable() == null) {
                return new Result.ResultBuiler().failed("添加的用户信息不完整！");
            }
            String date = DateUtil.getCurrentDateTime();
            cardUser.setCreateTime(date);
            cardUser.setUserStatus(0);
            cardUser.setOptId(sysStaff.getRowId());
            cardUser.setOptAccount(sysStaff.getStaffAccount());
//            cardUser.setEmailPwd(Crypter.encrypt(cardUser.getEmailPwd()));
//            cardUser.setLoginPwd(Crypter.encrypt(cardUser.getLoginPwd()));
//            cardUser.setPayPwd(Crypter.encrypt(cardUser.getPayPwd()));
            cardUser = cardUserService.saveObj(cardUser);
            return new Result.ResultBuiler().success(cardUser);
        } catch (Exception e) {
            log.error("添加的用户信息出错！", e);
            return new Result.ResultBuiler().error();
        }
    }


    /**
     * 修改用户信息
     *
     * @author 朱建文 创建时间：2018年4月17日 下午5:11:56
     */
    @ResponseBody
    @RequestMapping("/update")
    public Result update(CardUser cardUser, String token, HttpServletRequest request) {
        try {
            SysStaff sysStaff = tokenHandler.getSysStaffInfoByToken(token);
            if (sysStaff == null) {
                return new Result.ResultBuiler().failed("登录状态失效");
            }
            if (cardUser.getRowId() == 0) {
                return new Result.ResultBuiler().failed("修改的用户信息ID不能为空");
            }
            String date = DateUtil.getCurrentDateTime();
            cardUser.setUserStatus(0);
            cardUser.setLastOptTime(date);
            cardUser.setOptId(sysStaff.getRowId());
            cardUser.setOptAccount(sysStaff.getStaffAccount());
            cardUser.setFailId(0L);
            cardUser.setFailReason("");
            //cardUser.setFailTime("");
//            cardUser.setEmailPwd(Crypter.encrypt(cardUser.getEmailPwd()));
//            cardUser.setLoginPwd(Crypter.encrypt(cardUser.getLoginPwd()));
//            cardUser.setPayPwd(Crypter.encrypt(cardUser.getPayPwd()));
            cardUser = cardUserService.updateNotNullColumn(cardUser);
            if (cardUser != null) {
                return new Result.ResultBuiler().success(cardUser);
            } else {
                return new Result.ResultBuiler().failed("修改用户信息失败");
            }
        } catch (Exception e) {
            log.error("修改用户信息出错！", e);
            return new Result.ResultBuiler().error();
        }
    }

    /**
     * 获取用户列表数据
     */
    @ResponseBody
    @RequestMapping("/data")
    public AjaxPageData<CardUser> getUserPageList(OPaging<CardUser> page, HttpServletRequest request) {
        AjaxPageData<CardUser> dataPage = new AjaxPageData<CardUser>();
        try {
            page.setOrderBy(" ORDER BY CREATE_TIME DESC ");
            Paging<CardUser> pageData = cardUserService.findPage(page);
            if (pageData.getDataList() == null || pageData.getDataList().isEmpty()) {
				return dataPage;
			}
            
//            for (CardUserVO cardUser : pageData.getDataList()) {
//            	cardUser.setEmailPwd(Crypter.decrypt(cardUser.getEmailPwd()));
//            	cardUser.setLoginPwd(Crypter.decrypt(cardUser.getLoginPwd()));
//            	cardUser.setPayPwd(Crypter.decrypt(cardUser.getPayPwd()));
            	
//				cardUser.setEmailPwd(cardUser.getEmailPwd().substring(0, 3) + "*****" + cardUser.getEmailPwd().substring(cardUser.getEmailPwd().length() - 3));
//				cardUser.setLoginPwd(cardUser.getLoginPwd().substring(0, 3) + "*****" + cardUser.getLoginPwd().substring(cardUser.getLoginPwd().length() - 3));
//				cardUser.setPayPwd(cardUser.getPayPwd().substring(0, 3) + "*****" + cardUser.getPayPwd().substring(cardUser.getPayPwd().length() - 3));
//			}
            
            dataPage = getAjaxPageData(pageData);
        } catch (Exception e) {
            log.error("获取员工列表数据出错！", e);
        }
        return dataPage;
    }

    /**
     * 获取指定用户的信息
     */
    @ResponseBody
    @RequestMapping("/getUserDetail")
    public Result<CardUser> getUserDetail(Long rowId, HttpServletRequest request) {
        Result<CardUser> result = new Result<CardUser>();
        result.setCode(-1);
        result.setMessage("获取用户信息失败！");
        try {
            CardUser cardUser = this.cardUserService.findByPK(rowId);
//            cardUser.setEmailPwd(Crypter.decrypt(cardUser.getEmailPwd()));
//        	cardUser.setLoginPwd(Crypter.decrypt(cardUser.getLoginPwd()));
//        	cardUser.setPayPwd(Crypter.decrypt(cardUser.getPayPwd()));
            result.setCode(0);
            result.setData(cardUser);
            result.setMessage("获取用户信息成功！");
        } catch (Exception e) {
            log.error("获取指定用户的信息出错！", e);
        }
        return result;
    }

	/**
	 * 检查平台帐号是否存在
	 * 
	 * @author 朱建文 创建时间：2018年5月23日 下午3:30:50
	 */
	@ResponseBody
	@RequestMapping("/checkIsExist")
	public Result<String> checkPvsCIsexist(CardUser cardUser, HttpServletRequest request) {
		Result<String> result = new Result<String>();
		result.setCode(-1);
		result.setMessage("平台帐号已存在");
		try {
			SysStaff sysStaff = getLoginUser(request);
			if (sysStaff == null) {
				result.setCode(-2);
				result.setMessage("请重新登录!");
				return result;
			}
			Query query = new Query();
			query.put("PLATFORM_TYPE", cardUser.getPlatformType());
			query.put("USER_NAME", cardUser.getUserName());
			if (cardUser.getRowId() != null && cardUser.getRowId() > 0) {
				query.put("_NOT_EQUAL$ROW_ID", cardUser.getRowId());
			}
			boolean isExist = this.cardUserService.isExist(query);
			if (!isExist) {
				result.setCode(0);
				result.setMessage("可以录入!");
			}
		} catch (Exception e) {
			log.error("检查平台帐号是否存在出错！", e);
		}
		return result;
	}

    /**
     * 获取google验证码
     */
    @ResponseBody
    @RequestMapping("/getGoogleCode")
    public Result getGoogleCode(Long rowId, String token,int platformType, HttpServletRequest request) {
        Result result = new Result();
        result.setCode(-1);
        result.setMessage("获取验证码失败！");
        try {
            SysStaff sysStaff = tokenHandler.getSysStaffInfoByToken(token);
            if (sysStaff == null) {
                return new Result.ResultBuiler().failed("登录状态失效");
            }
            CardUser cardUser = this.cardUserService.findByPK(rowId);
            if (cardUser == null) {
                return result;
            }
            String code = CodeUtil.getCode(cardUser.getUserKey());
            result.setCode(0);
            result.setData(code);
            result.setMessage("获取验证码成功！");
            log.info(String.format("用户%s获取了%s的验证码", sysStaff.getStaffAccount(), cardUser.getUserName()));
            CardBaseGetCode cardBaseGetCode = new CardBaseGetCode();
            cardBaseGetCode.setStaffId(sysStaff.getRowId());
            cardBaseGetCode.setStaffName(sysStaff.getStaffAccount());
            cardBaseGetCode.setUserId(cardUser.getRowId());
            cardBaseGetCode.setUserName(cardUser.getUserName());
            cardBaseGetCode.setGetCode(code);
            cardBaseGetCode.setGetTime(DateUtil.getCurrentDateTime());
            cardBaseGetCode.setPlatformType(platformType);
            cardBaseGetCode.setUserKey(cardUser.getUserKey());

            baseDao.saveAll(cardBaseGetCode);
        } catch (Exception e) {
            log.error("获取验证码出错！", e);
        }
        return result;
    }


    /**
     * 新项目开始
     * 重新分配
     */
    @ResponseBody
    @RequestMapping(value = "/allocation", method = RequestMethod.POST)
    public Result allocation(String token, String projectName, Integer platformType,  HttpServletRequest request) {
        try {
            Map<Long, Integer> data;
        	String dataStr = getParamValueString(request, "data");
        	data = JsonUtil.toPOJO(dataStr, HashMap.class);
            SysStaff sysStaff = tokenHandler.getSysStaffInfoByToken(token);
            if (sysStaff == null) {
                return new Result.ResultBuiler().failed("登录状态失效");
            }
            if (StringUtil.isEmpty(projectName)) {
                return new Result.ResultBuiler().failed("未设置项目名称，不能进行分配");
            }
            if (data == null || data.isEmpty()) {
                return new Result.ResultBuiler().failed("未指定分配方案");
            }
            boolean resultBool = cardUserService.allocation(platformType, projectName, data, sysStaff);
            if (resultBool) {
                return new Result.ResultBuiler().success();
            } else {
                return new Result.ResultBuiler().failed("分配失败，请稍后再试");
            }
        } catch (Exception e) {
            log.error("分配任务出错！", e);
            return new Result.ResultBuiler().error();
        }
    }


    /**
     * 剩余分配
     */
    @ResponseBody
    @RequestMapping(value = "/residue/allocation", method = RequestMethod.POST)
    public Result residueAllocation(String token, Integer platformType, HttpServletRequest request) {
        try {
            Map<Long, Integer> data;
            String dataStr = getParamValueString(request, "data");
            data = JsonUtil.toPOJO(dataStr, new TypeReference<Map<Long, Integer>>() {});
            SysStaff sysStaff = tokenHandler.getSysStaffInfoByToken(token);
            if (sysStaff == null) {
                return new Result.ResultBuiler().failed("登录状态失效");
            }
            if (platformType == null || platformType==0) {
                return new Result.ResultBuiler().failed("未指定剩余分配平台");
            }
            if (data == null || data.isEmpty()) {
                return new Result.ResultBuiler().failed("未指定分配方案");
            }
            boolean resultBool = cardUserService.residueAllocation(platformType,data, sysStaff);
            if (resultBool) {
                return new Result.ResultBuiler().success();
            } else {
                return new Result.ResultBuiler().failed("分配失败，请稍后再试");
            }
        } catch (Exception e) {
            log.error("获取验证码出错！", e);
            return new Result.ResultBuiler().error();
        }
    }

    /**
     * 获取未分配的帐号数量
     * 
     * @author 朱建文 创建时间：2018年5月29日 下午4:59:20
     */
    @ResponseBody
    @RequestMapping("/getNotAllotAccountNum")
    public Result<Integer> getNotAllotAccountNum(Long platformType, HttpServletRequest request) {
    	Result<Integer> result = new Result<Integer>();
    	result.setCode(-1);
    	result.setMessage("获取未分配的帐号数量失败！");
    	try {
			String token = getParamValueString(request, "token");
			SysStaff sysStaff = tokenHandler.getSysStaffInfoByToken(token);
			if (sysStaff == null) {
				result.setMessage("登录状态异常！");
			    return result;
			}
			
			int count = this.cardUserService.getNotAllotNum(platformType);
			result.setCode(0);
			result.setData(count);
			result.setMessage("获取未分配的帐号数量成功！");
		} catch (Exception e) {
			log.error("获取未分配的帐号数量出错！", e);
		}
    	return result;
    }

    /**
     * 获取所有帐号数量
     *
     * @author 朱建文 创建时间：2018年5月29日 下午4:59:20
     */
    @ResponseBody
    @RequestMapping("/getAccountNum")
    public Result<Integer> getAccountNum(Long platformType, HttpServletRequest request) {
        Result<Integer> result = new Result<Integer>();
        result.setCode(-1);
        result.setMessage("获取未分配的帐号数量失败！");
        try {
            String token = getParamValueString(request, "token");
            SysStaff sysStaff = tokenHandler.getSysStaffInfoByToken(token);
            if (sysStaff == null) {
                result.setMessage("登录状态异常！");
                return result;
            }

            int count = this.cardUserService.getUseableNum(platformType);
            result.setCode(0);
            result.setData(count);
            result.setMessage("获取未分配的帐号数量成功！");
        } catch (Exception e) {
            log.error("获取未分配的帐号数量出错！", e);
        }
        return result;
    }
    
    /**
     * 批量导入帐号
     * 
     * @author 朱建文 创建时间：2018年6月6日 下午3:22:06
     */
    @ResponseBody
    @RequestMapping("/importExcelData")
    public Result<String> importExcelData(HttpServletRequest request, HttpServletResponse response){
    	Result<String> result = new Result<String>();
        result.setCode(-1);
        result.setMessage("批量导入帐号失败！");
        try {
			String token = getParamValueString(request, "token");
			SysStaff sysStaff = tokenHandler.getSysStaffInfoByToken(token);
			if (sysStaff == null) {
			    result.setMessage("登录状态异常！");
			    return result;
			}
			
			Result<List<CardUser>> importResult = this.excelHandler.ImportCardUserExcel(request);
			if (importResult.getCode() != 0) {
				result.setMessage(importResult.getMessage());
				return result;
			}
			
			if (importResult.getData() == null || importResult.getData().isEmpty()) {
				result.setMessage("未读取到有效数据！");
				return result;
			}
			
			for (CardUser cardUser : importResult.getData()) {
				cardUser.setOptId(sysStaff.getRowId());
				cardUser.setOptAccount(sysStaff.getStaffAccount());
				cardUser.setLastOptTime(DateUtil.getCurrentDateTime());
				this.cardUserService.saveObj(cardUser);
			}
			
			result.setCode(0);
			result.setMessage("导入成功！共导入" + importResult.getData().size() + "条数据！");
		} catch (Exception e) {
			log.error("批量导入帐号出错！", e);
		}
        return result;
    }
    
    /**
     * 保存布谷官网用户填写信息
     *
     * @author roway 创建时间：2018年7月20日 上午10:39:20
     */
    @ResponseBody
    @RequestMapping("/saveUserInfo")
    public Result<Integer> saveUserInfo(String userName, String userEmail,HttpServletRequest request) {
        Result<Integer> result = new Result<Integer>();
        result.setCode(-1);
        result.setMessage("保存用户信息 失败！");
        try {
        	CardBuguUserInfo cardBuguUserInfo = new CardBuguUserInfo();
        	cardBuguUserInfo.setUserName(userName);
        	cardBuguUserInfo.setUserEmail(userEmail);
        	cardBuguUserInfo.setCreateTime(DateUtil.getCurrentDateTime());
        	baseDao.saveAll(cardBuguUserInfo);
        	
            result.setCode(0);
            result.setMessage("保存用户信息 成功！");
        } catch (Exception e) {
            log.error("保存用户信息 出错！", e);
        }
        return result;
    }
    
    /**
     * 查询 官网用户提交联系方式
     * @return
     */
    @ResponseBody
    @RequestMapping("/bgUser/data")
    public AjaxPageData<CardBuguUserInfo> findBuguUserData(OPaging<CardBuguUserInfo> page, String token,String userName, String userEmail, HttpServletRequest request) {
        AjaxPageData<CardBuguUserInfo> dataPage = new AjaxPageData();
        try {
            SysStaff sysStaff = tokenHandler.getSysStaffInfoByToken(token);
            log.info("布谷官网用户提交联系方式被查询【"+sysStaff.getRowId()+sysStaff.getStaffAccount()+"】");
            if (sysStaff == null) {
                return dataPage;
            }
            Paging<CardBuguUserInfo> cardOptRecordPaging = cardUserService.findPage(page, userName,userEmail);
            return getAjaxPageData(cardOptRecordPaging);
        } catch (Exception e) {
            log.error("获取 布谷管理用户提交信息 列表数据出错！", e);
        }
        return dataPage;
    }
    
}
